import React, { useEffect, useState } from 'react'
import { Card, Modal, Input, Select, Space, Switch, InputNumber, Button } from "antd"
import { BorderOutlined } from '@ant-design/icons';
import type { TableColumnsType } from 'antd';
import { Image, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { useSnapshot } from "valtio";

import Htables from '@/components/Htables';
import { order } from "@/stores/Order"
import type { InputNumberProps } from 'antd';
import { useNavigate } from 'react-router-dom';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });
interface Child {
    key: number;
    name: string;
    dan: string;
    price: string;
    num: number;
}
export default function Comboshow() {
    const orders = useSnapshot(order)
    const { TextArea } = Input;
    const handleChanges = (value: string) => {
        setentity(value)
    };
    const weioptions = [
        { value: '份', label: '份' },
        { value: '盘', label: '盘' },
        { value: '个', label: '个' },
        { value: '瓶', label: '瓶' },
        { value: '斤', label: '斤' },
        { value: '升', label: '升' },
        { value: '毫升', label: '毫升' },
        { value: '克', label: '克' },
    ]
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState<UploadFile[]>([
        {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        },

    ]);
    const [children, setchildren] = useState([])
    const [name, setname] = useState('')
    const [shopname, setshopname] = useState('')
    const [price, setprice] = useState("")
    const [vipprice, setvipprice] = useState("")
    const [cost, setcost] = useState("")
    const [boxfee, setboxfee] = useState("")
    const [state, setstate] = useState(false)
    const [chiname, setchiname] = useState("")
    const [text, settext] = useState("")
    const [entity, setentity] = useState("")
    const [cprice, setcprice] = useState("")
    const [num, setnum] = useState(1)
    useEffect(() => {
        orders.getmax()
        setname(orders.maxshow.name)
        setshopname(orders.maxshow.shopname)
        setprice(orders.maxshow.price)
        setvipprice(orders.maxshow.vipprice)
        setcost(orders.maxshow.cost)
        setboxfee(orders.maxshow.boxfee)
        setchildren(orders.maxshow.children)
        setstate(orders.maxshow.state)
        settext(orders.maxshow.text)
    }, [])
    const handleDelete = (record) => {
        setchildren(orders.maxshow.children.filter((item) => item.key !== record.key))

    };
    const [columns, setcolumns]: TableColumnsType<DataType> = useState([
        {
            title: <BorderOutlined></BorderOutlined>,
            dataIndex: 'key',

        },
        {
            title: '名称',
            dataIndex: 'name',

        },
        {
            title: '单位',
            dataIndex: 'dan',
        },
        {
            title: '价格',
            dataIndex: 'price',
        },
        {
            title: '数量',
            dataIndex: 'num',
        },
        {
            title: (
                <span>
                    操作
                </span>
            ),
            render: (text: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => handleDelete(record)}><BorderOutlined></BorderOutlined>删除</a>
                </Space>
            ),
        }
    ]);

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as FileType);
        }
        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
    };

    const handleChangeimg: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setFileList(newFileList);
    }
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <BorderOutlined />
            <div style={{ marginTop: 8 }}>上传图片</div>
        </button>
    );
    const onChangetext = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        settext(e.target.value)
    };
    const onChangestate = (checked: boolean) => {
        setstate(checked)
    };
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const onChange: InputNumberProps['onChange'] = (value) => {
        setnum(value as number)
    };
    const nav = useNavigate()
    const addchirend = () => {
        setchildren(item => [
            ...item,
            {
                key: item.length + 1,
                name: chiname,
                dan: entity,
                price: cprice,
                num: num,
            }
        ]);
    }
    return (
        <div>
            <Modal title="套餐详细" open={isModalOpen} onOk={handleOk} footer={false} onCancel={handleCancel}>
                <p className='flex '>名称：<Input placeholder='请输入' style={{ width: 360 }} value={chiname} onChange={(e) => {
                    setchiname(e.target.value)
                }}></Input></p>
                <p>单位：<Select
                    defaultValue="lucy"
                    value={entity}
                    style={{ width: 360 }}
                    onChange={handleChanges}
                    options={weioptions}
                /></p>
                <p className='flex '>价格：<Input placeholder='请输入' style={{ width: 360 }} value={cprice} onChange={(e) => {
                    setcprice(e.target.value)
                }}></Input></p>
                <p>数量：<InputNumber value={num} onChange={onChange} changeOnWheel /></p>
                <div className="flex justify-end mt-[30px] border-t-2">
                    <Button onClick={handleCancel}>取消</Button>
                    <Button type="primary" onClick={() => {
                        addchirend()
                    }}>确定</Button>
                </div>
            </Modal>
            <Card bodyStyle={{ padding: 0 }} className='w-[90%] m-auto mt-10 h-[65vh] pb-[20px]' >
                <header className='p-0 pl-3 h-[35px] bg-#eee text-[20px] item-center'>套餐信息</header>
                <div className='m-auto w-[50%] items-center pd-[10px]'>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>店铺名称：</p><Input value={shopname} onChange={(e) => {
                        setshopname(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>套餐名称：</p><Input value={name} onChange={(e) => {
                        setname(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>套餐售价：</p><Input value={price} onChange={(e) => {
                        setprice(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>套餐会员价：</p><Input value={vipprice} onChange={(e) => {
                        setvipprice(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>外卖价：</p><Input value={cost} onChange={(e) => {
                        setcost(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>餐盒费：</p><Input value={boxfee} onChange={(e) => {
                        setboxfee(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>商品图片：</p>
                        <Upload
                            action="http://127.0.0.1:3000/upload"
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onChange={handleChangeimg}
                        >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>
                        {previewImage && (
                            <Image
                                wrapperStyle={{ display: 'none' }}
                                preview={{
                                    visible: previewOpen,
                                    onVisibleChange: (visible) => setPreviewOpen(visible),
                                    afterOpenChange: (visible) => !visible && setPreviewImage(''),
                                }}
                                src={previewImage}
                            />
                        )}
                    </div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>餐盒描述：</p>
                        <TextArea
                            showCount
                            maxLength={100}
                            value={text}
                            onChange={onChangetext}
                            placeholder="disable resize"
                            style={{ height: 120, resize: 'none' }}
                        />
                    </div>
                    <div className='flex items-center w-[100%] mt-[10px] '><p className='w-[90px]'>上架状态：</p><Switch defaultChecked value={state} onChange={onChangestate} /></div>
                </div>
            </Card>
            <Card bodyStyle={{ padding: 0 }} extra={<a href="#"></a>} className='w-[90%] m-auto  h-[80vh] p-0' >
                <header className='flex p-0 justify-between pl-3 h-[50px] bg-#eee text-[15px] item-center'>
                    <p>套餐明细</p>
                    <p className='color-blue' onClick={showModal}><BorderOutlined></BorderOutlined>添加商品</p>
                </header>
                <Htables columns={columns} data={children}></Htables>
            </Card>
            <footer className='w-[90%] h-[55px] bg-#eee text-[20px] m-auto item-center'>
                <div className='w-[100%] flex justify-center'>
                    <Button className='mr-10' onClick={() => {
                        nav(-1)
                    }}>取消</Button>
                    <Button type="primary" onClick={() => {
                        orders.editmax(name, shopname, cost, boxfee, children, price, vipprice, state, chiname, entity, cprice, num)
                    }}>确定</Button>
                </div>
            </footer>
        </div >
    )
}
